/*
 *	TankMania/GPanel.java
 *
 *  TankMania/GPanel.class
 *
 * (C) 王宏伟 2008010486 计84 清华大学
 * 
 */

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;

public class GPanel extends JPanel implements ActionListener
{
	public Graphics2D g;
	public BufferedImage map;
	public BufferedImage fight;
	public Chat chat;
	public static ClientData data;
	public static ClientTime time;
	public Timer timer;
	
	public GPanel(Chat chat)
	{
		super();
		this.chat = chat;
		timer = new Timer(time.updateRound,this);
		map = readImage("map");
		this.setVisible(true);
		this.setSize(map.getWidth(),map.getHeight());
		fight = new BufferedImage(map.getWidth(),map.getHeight()+25,BufferedImage.TYPE_INT_RGB);
		g = fight.createGraphics();
	}
	public void start()
	{
		timer.start();
	}
	public void actionPerformed(ActionEvent e)
	{
		draw();
	}
	public void paint(Graphics g)
	{
		g.drawImage(fight,0,0,this);
	}
	
	public void update(Graphics g) 
	{ 
		paint(g);
		g.drawImage(fight, 0, 0, this); 
	}
	
	public void draw()
	{
		int x,y;
		g.drawImage(map,0,0,this);
		int i;
		for(i = 0;i < chat.tankNum ;i++)
			tank(data.tank[chat.tankID[i]]);
		for(i = 0;i < 100;i++)
			if(data.bullet[i].isShow)
				bullet(data.bullet[i]);
		for(i = 0;i < chat.tankNum ;i++)
		{
			Tank tank = data.tank[chat.tankID[i]];
			String str = new String(tank.name+":"+tank.life);
			y = tank.y-20;
			if(y <= 10)	y = 50;
			g.drawString(str,tank.x-str.length()*3,y);
			if(tank.isShow)
			{			
				y = tank.y-40;
				if(y < 10) y = tank.y+50;
				if(y >= 10  && y < 20)	y = tank.y+30;
				g.drawString(tank.chatStr,tank.x-tank.chatStr.length()*3,y);
				tank.chatDie();
			}
		}
		repaint();
	}
	
	public void create(String str,int x,int y,int d)
	{
		BufferedImage image = readImage(str);
		int w = image.getWidth();
		int h = image.getHeight();
		g.rotate(d*Math.PI/180,x,y);
		g.drawImage(image,x-w/2,y-h/2,this);
		g.rotate(-d*Math.PI/180,x,y);
		repaint();
	}
	public void bullet(Bullet bullet)
	{
		create("bullet",bullet.x,bullet.y,bullet.angle+90);
	}
	public void tank(Tank tank)
	{
		create("tank",tank.x,tank.y,tank.angle+90);
		create("gun",tank.x,tank.y,tank.gunAngle+90);
		if(tank.isHited)
		{	
			create("hit",tank.x,tank.y,0);
			tank.hitDie();
		}
	}
	
	public BufferedImage readImage(String str)
	{
		File file;	
		BufferedImage image = null;
		try{
			file = new File(str+".png");
			image =  ImageIO.read(file);
		}catch(Exception e){
			System.out.println("Error!");
			System.exit(0);
		}
		return image;
	}
}


